<!--
 * @Autor: 黄旗
 * @Date: 2020-06-03 16:04:09
-->
<template>
    <div style="position: relative; height: 100%;">
        <div class="wrapper" ref="wrApper" @mousewheel="handleScroll">
            <div v-if="chatrecordlist && chatrecordlist.length">
                <div v-for="(item, index) in chatrecordlist" :id="`id-${item.id}`" :key="item.index" :class="item.isSend ? 'right times' : 'left times'">
                    <div class="name">
                        <div>
                            <img :src="item.avatar || baseImg" style="margin-right: 15px;">
                        </div>
                        <div class="names">
                            <p style="margin-right: 15px;">{{ item.name }}</p>
                            <p style="margin-right: 15px;">
                                {{ changetime(item.create_time) }}
                            </p>
                        </div>
                    </div>
                    <div class="content">
                        <!-- 1：文字  2：图片 3：语音   4:视频消息  5：系统提示  8 : 文件 11:红包 12:转账 14 : 表情  20: 语音通话/视频通话 -->
<!--                        <template v-if="parseInt(item.deleted) === 1">
                            <span style="color:darkgray">消息已撤回</span>
                        </template>-->
                        <!-- 图片 -->
                        <template v-if="parseInt(item.contentType) === 2">
                            <img class="image large-img" :src="decode(item)" @click="leftimgClick(item)">
                        </template>
                        <!-- 语音 -->
                        <template v-else-if="parseInt(item.contentType) === 3">
                            <Button v-if="item.show" type="primary" :disabled="item.loading && item.show" :loading="item.loading" @click="toLoading(index)">
                                <span v-if="!item.loading">加载音频</span>
                                <span v-else>加载中...</span>
                            </Button>
                            <audio :src="decode(item)" controls v-else></audio>
                        </template>
                        <!-- 视频 -->
                        <template v-else-if="parseInt(item.contentType) === 4">
                            <div class="video-box">
                                <img :src="decode(item)" alt="视频" />
                                <div class="video-boxs" @click="leftvideoClick(item)">
                                    <i class="ivu-icon ivu-icon-md-arrow-dropright-circle"></i>
                                </div>
                            </div>
                        </template>
                        <!-- 其他消息 -->
                        <div class="wechatchat" v-else v-html="decode(item)"></div>
                    </div>
                </div>
            </div>
            <div v-else class="norecord">暂无聊天信息</div>
        </div>
        <!--loading-->
        <Spin size="large" fix v-if="spinShow"></Spin>
        <!--搜索聊天记录-->
        <div class="wrapper position" v-show="loadings">
            <div v-if="chatrecordlistss && chatrecordlistss.length > 0">
                <div v-for="item in chatrecordlistss" :id="`ids-${item.id}`" :key="item.index" :class="item.isSend ? 'right times posi' : 'left times posi'" @click="clickposi(item.id)">
                    <div class="name">
                        <div>
                            <img :src="item.avatar || baseImg" style="margin-right: 15px;">
                        </div>
                        <div class="names">
                            <p style="margin-right: 15px;">{{ item.name }}</p>
                            <p style="margin-right: 15px;">
                                {{ changetime(item.create_time) }}
                            </p>
                        </div>
                    </div>
                    <div class="content">
                        <div class="wechatchat"
                            v-if="
                                +item.contentType === 1 ||
                                    +item.contentType === 5 ||
                                    +item.contentType === 8 ||
                                    +item.contentType === 19 ||
                                    +item.contentType === 20
                            "
                            v-html="decode(item)"></div>
                    </div>
                </div>
            </div>
            <div v-else class="norecord">暂无搜索信息</div>
        </div>
        <!--底部操作-->
        <div class="ivu-mt-8 bottoms" v-if="chatrecordlist && chatrecordlist.length">
            <Row type="flex" justify="space-between" class="code-row-bg">
                <Col>
                    <Button type="info" @click="askData('all')" :disabled="disabled">加载全部</Button>
                    <Button class="ivu-ml-8" type="info" @click="exportchat" :disabled="chatrecordlist.length<1">导出图片</Button>
                    <Button class="ivu-ml-8" type="success" @click="repairPictures" :disabled="chatrecordlist.length<1|| showdis">修复图片</Button>
                </Col>
                <Col>
                    <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_first === 0 || disabled" @click="askData('first')">首次</Button>
                    <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_prev === 0 || disabled" @click="askData('prev')">上次</Button>
                    <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_next === 0 || disabled" @click="askData('next')">下次</Button>
                    <Button class="ivu-mr-8" type="info" :disabled="+disables.is_show_end === 0 || disabled" @click="askData('end')">尾次</Button>
                </Col>
            </Row>
        </div>

        <Modal v-model="modal" draggable footer-hide>
            <p style="text-align: center;font-size:16px">正在修复聊天记录中的图片，稍后请刷新</p>
        </Modal>

        <!--查看大图弹框-->
        <Modal v-model="content" draggable @on-cancel="handleCancel" footer-hide>
            <p slot="header" style="height:32px;width:90%">
                <Row type="flex" justify="space-between" align="middle" v-if="is_img">
                    <Col>查看大图</Col>
                    <Col>
                        <Button v-if="+this.id!==0 && butshow" :disabled="+src.is_medical_img === 1" type="primary" @click="addcase(src.id)">添加到病历</Button>
                    </Col>
                </Row>
            </p>
            <img :src="bigImgUrl" style="width: 100%;" v-if="is_img">
            <video v-if="!is_img" style="width:100%;height: 80vh;:80vh;object-fit: contain;" :src="bigImgUrl" controls type="video/mp4" alt="视频"></video>
        </Modal>
    </div>
</template>

<script>
    import Cookies from 'js-cookie';
    import {
        customerwechatmessagelist,
        customerwechatconverfile,
        patientindexaddmedicalimg,
        wechatmessagefileQueue,
        wechatMessageInfo
    } from '@/api/robot.js';
    import dayjs from 'dayjs';
    import phiz from '@/libs/phiz.js';
    export default {
        props: ['paramsrecord'],
        data () {
            return {
                baseImg: require('@/assets/images/avater.png'),
                firstshow: true,
                butshow: false,
                id: 0,
                loadings: false,
                spinShow: false,
                chatrecordlistss: [],
                chatrecordlist: [],
                now_date: '',
                disables: '',
                disabled: false,
                modal: false,
                state: true,
                showdis: false,
                scrollTop: 0,
                // 大图弹框
                src: {
                    id: 0,
                    is_medical_img: 0
                },
                content: false,
                is_img: false,
                bigImgUrl: ''
            };
        },
        watch: {
            footData () {
                this.scrollTop();
            }
        },
        mounted () {
            this.$nextTick(() => {
                // //监听这个dom的scroll事件
                this.$refs.wrApper.addEventListener('scroll', this.handleScroll);
            // 监听这个dom的scroll事件
            // this.wrapper.addEventListener("scroll", this.handleScroll);
            });
            //  this.wrApper.onscroll = () => {
            //   console.log("on scroll");
            //   this.handleScroll();
            // };
            if (this.$route.path === '/business/robot/chatRecord') {
                this.butshow = true;
            }
        },
        activated () {
            this.$refs.wrApper.scrollTop = this.scrollTop;
        },
        methods: {
            handleScroll () {
                // console.log('===scrool===')
                this.scrollTop = this.$refs.wrApper.scrollTop;
                Cookies.set('dengta-scroll', this.scrollTop)
                // console.log(this.scrolled )
                // 获取dom滚动距离
                // const scrollTop = this.wrApper.scrollTop;
                // 获取可视区⾼度
                const offsetHeight = this.$refs.wrApper.offsetHeight;
                // console.log(offsetHeight,'offsetHeight')
                // 获取滚动条总⾼度
                const scrollHeight = this.$refs.wrApper.scrollHeight;
            // console.log(scrollHeight,'scrollHeight')
            // xqConList 为⽬录内容列表
            // for (let i = 0; i < this.chatrecordlist.length - 1; i++) {
            //     //offsetTop: 获取当前元素到其定位⽗级（offsetParent）的顶部距离
            //     let offset_before = this.$el.querySelector("#xqItem" + i).offsetTop;
            //     let offset_after = this.$el.querySelector("#xqItem" + (i + 1)).offsetTop;
            //     //根据xqItem离顶部距离判断滚动距离落在哪两个item之间
            //     if (scrollTop >= offset_before && scrollTop < offset_after) {
            //     console.log("offset", offset_before, offset_after, scrollTop);
            //     console.log("scrollHeight", scrollTop, offsetHeight, scrollHeight);
            //     //判断是否滚动到了底部
            //     if (scrollTop + offsetHeight >= scrollHeight) {
            //         // 把距离顶部的距离加上可视区域的⾼度等于或者⼤于滚动条的总⾼度就是到达底部
            //         // console.log("已滚动到底部");
            //         if (this.menuActive < i) {
            //         this.menuActive = i;
            //         }
            //     } else {
            //         this.menuActive = i;
            //     }
            //     break;
            //     }
            // }
            },
            addcase (message_id) {
                patientindexaddmedicalimg({ message_id, id: this.id }).then(res => {
                    this.$Message.success({
                        content: '添加病历成功'
                    });
                    this.src.is_medical_img = 1;
                });
            },
            askData (type) {
                let id = Cookies.get(`dengta-oldid`)
                this.scrollTop = Cookies.get(`dengta-scroll`)
                this.$refs.wrApper.scrollTop = this.scrollTop;
                // console.log(this.$refs.wrApper.scrollTop,'111')
                //  console.log(scrol,'scrol')
                if (this.paramsrecord.id !== id) {
                    this.showdis = false
                } else {
                    this.showdis = true
                }
                // this.logs(type);
                this.chatrecordlistss = [];
                this.loadings = false;
                let config = {
                    wechat_id: this.paramsrecord.wechat_id,
                    friend_id: this.paramsrecord.friend_id,
                    date: this.paramsrecord.date,
                    type: type,
                    now_date: this.now_date
                };
                this.disabled = type === 'all';
                this.spinShow = true;
                customerwechatmessagelist(config).then(res => {
                    this.id = res.patient_info.id;
                    this.$emit('total', res.total);
                    let info = { friend_info: res.friend_info, patient_info: res.patient_info };
                    this.$emit('clickkeyword', info);
                    this.chatrecordlist = res.list.reverse();
                    if (res.list.length > 0) {
                        this.now_date = dayjs(res.list[0].create_time).format(
                            'YYYY-MM-DD'
                        );
                    }
                    this.disables = res.op;
                    for (let item of this.chatrecordlist) {
                        if (+item.contentType === 3) {
                            if (
                                item.content.indexOf('.amr') !== -1 ||
                                item.content.indexOf('.AMR') !== -1
                            ) {
                                item.show = true;
                                item.loading = false;
                            } else {
                                item.show = false;
                            }
                        }
                    }
                    this.spinShow = false;
                    this.firstshow = false;
                });
            },
            askDatacancel () {
                this.loadings = false;
                this.chatrecordlist = [];
                this.chatrecordlistss = [];
            },
            exportchat () {
                let apiBaseURL = this.$Setting.apiBaseURL;
                let url = '/v1/customer/wechat/download-message';
                let wechat_id = `wechat_id=${this.paramsrecord.wechat_id}`;
                let friend_id = `friend_id=${this.paramsrecord.friend_id}`;
                let urls = `${apiBaseURL}${url}?${wechat_id}&${friend_id}`;
                // window.location.href = urls
                window.open(urls);
            },
            // 修复图片
            repairPictures () {
                var millisecond = new Date().getTime();
                var expiresTime = new Date(millisecond + 60 * 1000 * 3);

                Cookies.set('dengta-oldid', this.paramsrecord.id, {
                    expires: expiresTime
                });

                if (this.state) {
                    this.state = false;
                    const params = {
                        wechatid: this.paramsrecord.wechat_id,
                        friendid: this.paramsrecord.friend_id
                    };
                    wechatmessagefileQueue(params).then(res => {
                        this.modal = true;
                        this.showdis = true;
                        setTimeout(() => {
                            // console.log(111);
                            this.state = true;
                            this.showdis = false;
                        }, 180000);
                    }).catch(() => {
                        this.modal = false;
                    });
                }
            },
            askDatas () {
                document.querySelector('.wrapper').scrollTop = 0;
                let config = {
                    wechat_id: this.paramsrecord.wechat_id,
                    friend_id: this.paramsrecord.friend_id,
                    keywords: this.paramsrecord.keywords,
                    date: this.paramsrecord.date
                };
                if (this.paramsrecord.keywords !== '') {
                    this.loadings = true;
                    customerwechatmessagelist(config).then(res => {
                        this.id = res.patient_info.id;
                        this.chatrecordlistss = res.list.reverse();
                        for (let item of this.chatrecordlistss) {
                            if (+item.contentType === 1) {
                                let key = this.paramsrecord.keywords;
                                if (key !== '') {
                                    if (item.content.indexOf(key) !== -1) {
                                        item.content = item.content.replace(
                                            key,
                                            `<font color="#42a2e2">${key}</font>`
                                        );
                                    }
                                }
                            }
                        }
                    });
                } else {
                    this.chatrecordlistss = [];
                    this.loadings = false;
                }
            },
            clickposi (id) {
                this.$nextTick(() => {
                    this.loadings = false;
                    let scrollHeight = document.querySelector(`#id-${id}`)
                        .offsetTop;
                    document.querySelector('.wrapper').scrollTop =
                        scrollHeight - 10;
                    this.logs(scrollHeight, id);
                });
            },
            changetime (time) {
                let timer = time.split(' ')[1];
                let dates = new Date();
                let date = new Date(time);
                let year = date.getFullYear();
                let years = dates.getFullYear();
                let month = date.getMonth();
                let months = dates.getMonth();
                let day = date.getDate();
                let days = dates.getDate();
                let times = '';
                if (year === years) {
                    if (month === months) {
                        if (days - day > 1) {
                            times = time;
                        } else if (days - day > 0) {
                            times = `昨天${timer}`;
                        } else {
                            times = `今天${timer}`;
                        }
                    } else {
                        times = time;
                    }
                } else {
                    times = time;
                }
                return times;
            },
            toLoading (index) {
                this.chatrecordlist[index].loading = true;
                this.chatrecordlist = JSON.parse(
                    JSON.stringify(this.chatrecordlist)
                );
                customerwechatconverfile({
                    id: this.chatrecordlist[index].id
                }).then(res => {
                    this.chatrecordlist[index].content = res.content;
                    this.chatrecordlist[index].loading = false;
                    this.chatrecordlist[index].show = false;
                    this.chatrecordlist = JSON.parse(
                        JSON.stringify(this.chatrecordlist)
                    );
                });
            },
            // 查看大图
            leftimgClick (item) {
                wechatMessageInfo({ id: item.id }).then(res => {
                    this.is_img = true;
                    this.content = true;
                    // 渲染数据
                    this.bigImgUrl = res.fileUrl || res.content;
                    this.src.id = item.id;
                    this.src.is_medical_img = item.is_medical_img;
                });
            },
            // 查看视频
            leftvideoClick (item) {
                wechatMessageInfo({ id: item.id }).then(res => {
                    this.is_img = false;
                    this.content = true;
                    // 渲染数据
                    this.bigImgUrl = res.content;
                });
            },
            handleCancel () {
                this.bigImgUrl = ''
            },
            // base64解码 & 不同类型的消息解读
            decode (chat) {
                let content = chat.content;
                let jcontent = {};
                let jsonReg = /^{.*}$/;
                let thumb = '';
                let str = '';
                try {
                    switch (parseInt(chat.contentType)) {
                    // 文本 1
                    case 'Text':
                    case 1:
                        return phiz.qqFaceImgMap(content);
                    // 图片 2
                    case 'Picture':
                    case 2:
                        if (jsonReg.test(content)) {
                            jcontent = JSON.parse(content);
                            thumb = jcontent.content ? jcontent.content : '../../assets/images/imgerror.png';
                        } else {
                            thumb = content;
                        }
                        return thumb;
                    // 语音 3
                    case 'Voice':
                    case 3:
                        thumb = content.replace(/.amr/, '.mp3');
                        str = thumb.replace(/.mp3:.*/, '.mp3');

                        // str = ` <audio src="${thumb}" alt="语音" controls></audio>`
                        return str;
                    // 视频 4
                    case 'Video':
                    case 4:
                        thumb = chat.thumb ? chat.thumb : '../../assets/images/imgerror.png';
                        return thumb;
                    // 系统消息 5
                    case 'System':
                    case 5:
                        return content;
                    // 链接消息 6
                    case 'Link':
                    case 6:
                        return '<div style="color:red">有超链接消息，请在手机查看</div>';
                    // 位置信息 10
                    case 'Location':
                    case 10:
                        return '<div style="color:red">有位置消息，请在手机查看</div>';
                    // 红包 11
                    case 'LuckyMoney':
                    case 11:
                        return '<div style="color:red">有红包，请在手机查看</div>';
                    // 转账 12
                    case 'MoneyTrans':
                    case 12:
                        return '<div style="color:red">有转账，请在手机查看</div>';
                    // Emoji 14
                    case 'Emoji':
                    case 14:
                        if (chat.IsSend === 1) {
                            return `Emoji消息：${content}`;
                        } else {
                            if (jsonReg.test(content)) {
                                jcontent = JSON.parse(content);
                                thumb = jcontent.Thumb ? jcontent.Thumb : '../../assets/images/imgerror.png';
                            } else {
                                thumb = content;
                            }
                            str = `<img class="chat-img" src="${thumb}" alt="图片"/>`;
                            return str;
                        }
                    default:
                        return `不支持的消息，请去手机查看`;
                    }
                } catch (error) {
                    return chat.contentType + '消息：' + content;
                }
            }
        }
    };
</script>

<style lang="less" scoped>
.wrapper {
    width: 100%;
    border-radius: 5px;
    height: 90%;
    padding: 10px;
    background: #eee;
    box-sizing: border-box;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    //   background: #f3f3f3;
    overflow: auto;
    h3 {
        display: inline-block;
    }
    .create_time {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .wrappertitle {
        margin: 10px 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .right {
        // text-align: right;
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .name {
            flex-direction: row-reverse;
            .names {
                text-align: right;
            }
            img {
                margin-right: 0 !important;
            }
        }

        .content {
            .wechatchat {
                padding: 10px 15px;
                margin-bottom: 20px;
                background-color: #dae9f2;
                // text-align: center;
                border-radius: 8px;
                // box-shadow: 2px 2px 5px #000;
            }
        }
    }

    .left {
        // text-align: right;
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        .content {
            .wechatchat {
                padding: 10px 15px;
                margin-bottom: 20px;
                background-color: #fff;
                // text-align: center;
                border-radius: 8px;
                // box-shadow: 2px 2px 5px #000;
            }
        }
    }
    .content {
        margin: 0 51px;
    }

    .name,
    .more {
        color: #42a2e2;
        margin-bottom: 10px;
    }

    .name {
        display: flex;
        align-items: center;
        justify-content: center;

        img {
            width: 36px;
            height: 36px;
        }
    }

    .more {
        cursor: pointer;
    }

    .content {
        .money {
            display: flex;
            align-items: center;
            width: 300px;
            height: 50px;
            padding: 10px;
            background: #fa9d3b;
            border-radius: 10px;

            .text {
                margin-left: 20px;
                color: #fff;
                font-weight: bold;
            }
        }

        .image {
            height: 100px;
        }

        .video-item {
            height: 300px;
        }

        .large-img {
            cursor: pointer;
        }
    }

    /*定义滚动条宽高及背景，宽高分别对应横竖滚动条的尺寸*/

    &::-webkit-scrollbar {
        width: 10px;
        /*对垂直流动条有效*/
        height: 10px;
        /*对水平流动条有效*/
    }

    /*定义滚动条的轨道颜色、内阴影及圆角*/
    &::-webkit-scrollbar-track {
        // -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
        background-color: #fff;
        border-radius: 3px;
    }

    /*定义滑块颜色、内阴影及圆角*/
    &::-webkit-scrollbar-thumb {
        border-radius: 7px;
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
        // background-color: #ccc;
        background-color: #eee;
    }

    // /*定义两端按钮的样式*/
    // &::-webkit-scrollbar-button {
    // background-color:cyan;
    // }

    /*定义右下角汇合处的样式*/
    &::-webkit-scrollbar-corner {
        background: khaki;
    }

    .norecord {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .posi {
        cursor: pointer;
    }
}

.bottoms {
    // display: flex;
    // justify-content: center;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 90%;
    // margin: auto;
}

.video-box {
    position: relative;
    max-height: 200px;
    overflow: hidden;
    &s {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28px;
    }
}
</style>
